/**
 * Created by zhangyida on 15/12/28.
 */
import React, { PixelRatio } from 'react-native';
import Dimensions from 'Dimensions';
import { Key } from './key';
import DeviceInfo from 'react-native-device-info';


export var Utils = {
    //版本检测控制
    version: '1.7',
    versionCheck: '',
    //单位像素
    pixel: 1 / PixelRatio.get(),

    //屏幕尺寸
    size: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height
    },

    //post请求
    post: function (url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                "enctype": "application/json",
                "Content-type": "application/json",
            },
            body: JSON.stringify(data)
        };
        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            });
    },
    //自带headers的传输
    transport: function (url, data, callback) {
        var params = {
            method: 'POST',
            headers: {
                "enctype": "application/json",
                "Content-type": "application/json",
                "username": Key.username,
                "ID": DeviceInfo.getUniqueID()
            },
            body: JSON.stringify(data)
        };
        fetch(url, params)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            });
    },

    transport1: function (url, data = {}, callback) {
        var params = {
            method: 'POST',
            headers: {
                "enctype": "application/json",
                "Content-type": "application/json",
                "username": Key.username,
                "ID": DeviceInfo.getUniqueID()
            },
            body: JSON.stringify(data)
        };
        fetch(url, params)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).catch((error) => {
                console.warn(error);
                throw error;
            });
    },


    //get请求
    get: function (url, callback) {
        console.log(url)
        return fetch(url)
            .then((response) => { 
                console.log(response);
                return response.text()
            })
            .then((responseText) => {
                callback(JSON.parse(responseText));
            })
            .catch((error) => {
                console.warn(error);
                throw error;
            })
    },

    get1: function (url, callback) {
        fetch(url)
            .then((response) => response.text())
            .then((responseText) => {
                callback(responseText);
            });
    },
};
